package com.kldy8.kldyw;

import android.app.Fragment;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.URLUtil;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.kldy8.kldyw.filmfactory.FilmTalent.FilmTalentActivity;
import com.kldy8.kldyw.filmfactory.company.CompanyActivity;
import com.kldy8.kldyw.filmfactory.dteam.DteamListActivity;
import com.kldy8.kldyw.filmfactory.equipment.DeviceActivity;
import com.kldy8.kldyw.filmfactory.shootingvenue.ShootingVenueActivity;
import com.kldy8.kldyw.logre.LoginActivity;
import com.kldy8.kldyw.model.WebViewJavascriptBridgeDataOrder;
import com.kldy8.kldyw.model.WebViewJavascriptBridgeOrder;
import com.kldy8.kldyw.system.ServerApi;
import com.kldy8.kldyw.system.ServerCallBack;
import com.kldy8.kldyw.system.UrlBuilder;
import com.kldy8.kldyw.web.AppWebUrl;
import com.kldy8.kldyw.web.MyJavaScriptInterface;
import org.json.JSONException;
import org.json.JSONObject;

import cn.sharesdk.onekeyshare.OnekeyShare;
import okhttp3.Request;


/**
 * Created by Administrator on 2016/7/18.
 */

public class Mine2Fragment extends Fragment  implements MyJavaScriptInterface
{
    private Toolbar toolbar;
    private MenuItem message_menu_item;
    private WebView webView;
    private String urlString;
    private String news_id;
    private Main2Activity activity;

    private RelativeLayout reloadlayout;
    private RelativeLayout loadinglayout;
    private ImageView reload_img;


    public static Mine2Fragment newInstance(String param1)
    {
        Mine2Fragment fragment = new Mine2Fragment();
        Bundle args = new Bundle();
        args.putString("agrs1", param1);
        fragment.setArguments(args);
        return fragment;
    }

    public Mine2Fragment()
    {

    }

    Drawable drawableLingRed;
    Drawable drawableLingNotRed;

    @Override
    public void onStart()
    {
        super.onStart();
        drawableLingRed =  getActivity().getApplication().getResources().getDrawable(R.drawable.icon_nmc_msg_dot);
        drawableLingNotRed  = getActivity().getApplication().getResources().getDrawable(R.drawable.icon_nmc_msg);
        String token =  SystemSet.getInstance().getToken();
        if (token != null && token.length()>0 && !token.equals("")) {
            ServerApi.message_count(token, new ServerCallBack()
            {
                @Override
                public void onError(Request request, Exception e)
                {

                }

                @Override
                public void onResponse(String response) throws JSONException
                {
                    JSONObject jsonObject = new JSONObject(response);
                    int date = jsonObject.optInt("data");
                    if (date != 0)
                    {
                        Log.e("data",response);
                        message_menu_item.setIcon(drawableLingRed);
                    }
                }
            });
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.fragment_mine2, container, false);
        urlString = AppWebUrl.createUrl(AppWebUrl.URL_PERSON_MANGER);
        Log.e("Mine2Fragment",urlString);
        init(view,urlString);
        activity = (Main2Activity) getActivity();


        return view;
    }

    private void init(View view, final String urlString)
    {
        toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        toolbar.setTitle(getResources().getString(R.string.hyzx));//设置主标题
        toolbar.inflateMenu(R.menu.menu_mine);
        message_menu_item = toolbar.getMenu().getItem(0);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener()
        {
            @Override
            public boolean onMenuItemClick(MenuItem item)
            {
                Intent intent = new Intent();
                String resultUrl = "";
                switch (item.getItemId())
                {
                    case R.id.action_nmc_msg:
                        resultUrl = AppWebUrl.createUrl(AppWebUrl.URL_MESSAGE);
                        intent.putExtra("url",resultUrl);
                        intent.setClass(activity, MyWebActivity.class);
                        item.setIcon(drawableLingNotRed);
                        activity.startActivityRightToLeft(intent);
                        break;
                    case R.id.action_nmc_setting:
                        resultUrl = AppWebUrl.createUrl(AppWebUrl.URL_USER_SETTING);
                        intent.putExtra("url",resultUrl);
                        intent.setClass(activity, MyWebActivity.class);
                        activity.startActivityRightToLeft(intent);
                        break;
                }
                return true;
            }
        });

        loadinglayout = (RelativeLayout) view.findViewById(R.id.loadinglayout);
        reloadlayout = (RelativeLayout) view.findViewById(R.id.reloadlayout);
        reload_img = (ImageView) view.findViewById(R.id.reload_img);
        reload_img.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                loadinglayout.setVisibility(View.VISIBLE);
                webView.loadUrl(urlString);
            }
        });



        webView = (WebView) view.findViewById(R.id.webView);
        WebSettings settings = webView.getSettings();
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setJavaScriptEnabled(true);
        //WebView加载web资源
        webView.loadUrl(urlString);
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webView.setWebViewClient(new WebViewClient()
        {
            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl)
            {
                // TODO Auto-generated method stub
//                super.onReceivedError(view, errorCode, description, failingUrl);
                loadinglayout.setVisibility(View.GONE);
                reloadlayout.setVisibility(View.VISIBLE);
            }
            @Override
            public void onPageFinished(WebView view, String url)
            {
                super.onPageFinished(view, url);
                loadinglayout.setVisibility(View.GONE);
            }

            @Override
            public boolean shouldOverrideUrlLoading(final WebView view, String url)
            {
                reloadlayout.setVisibility(View.GONE);
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                try {
                    url = AppWebUrl.createUrl(url);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Log.e("this is Mine my Url",url);

                if (url.contains("10086"))
                {
                    onReceivedError( view, 500,
                            "fuck", url);
                    return true;
                }
                if (!url.contains("kldy")&&(!url.contains("http://192.168.1.200")))
                {
                    onReceivedError( view, 500,
                            "fuck", url);
                    return true;
                }
                if (url.contains(UrlBuilder.URL_BASE_API+"/index.php/user/login")||url.contains(UrlBuilder.URL_BASE_API+"/user/login"))
                {
                    Intent intent = new Intent();
                    intent.setClass(activity, LoginActivity.class);
                    activity.startActivityRightToLeft(intent);
                    return true;
                }
                if (url.contains(UrlBuilder.URL_BASE_API+"/job/person_list"))
                {
                    Intent intent = new Intent();
                    intent.setClass(activity, FilmTalentActivity.class);
                    intent.putExtra("item",0);
                    activity.startActivityRightToLeft(intent);
                    return true;
                }
                if (url.contains(UrlBuilder.URL_BASE_API+"/job/company_list"))
                {
                    Intent intent = new Intent();
                    intent.setClass(activity, FilmTalentActivity.class);
                    intent.putExtra("item",1);
                    activity.startActivityRightToLeft(intent);
                    return true;
                }
                if (url.contains(UrlBuilder.URL_BASE_API+"/dteam/dteam_list"))
                {
                    Intent intent = new Intent();
                    intent.putExtra("item",0);
                    intent.setClass(activity, DteamListActivity.class);
                    activity.startActivityRightToLeft(intent);
                    return true;
                }
                if (url.contains(UrlBuilder.URL_BASE_API+"/place/place_list")) {
                    Intent intent = new Intent();
                    intent.putExtra("item", 0);
                    intent.setClass(activity, ShootingVenueActivity.class);
                    activity.startActivityRightToLeft(intent);
                    return true;
                }
                if (url.contains(UrlBuilder.URL_BASE_API+"/device/device_list"))
                {
                    Intent intent = new Intent();
                    intent.putExtra("item",0);
                    intent.setClass(activity, DeviceActivity.class);
                    activity.startActivityRightToLeft(intent);
                    return true;
                }
                if (url.contains(UrlBuilder.URL_BASE_API+"/company/company_list"))
                {
                    String type = "15";
                    if (url.contains("type_id=15"))
                    {
                        type = "15";
                    }
                    if (url.contains("type_id=14"))
                    {
                        type = "14";
                    }
                    if (url.contains("type_id=16"))
                    {
                        type = "16";
                    }
                    if (url.contains("type_id=17"))
                    {
                        type = "17";
                    }
                    Intent intent = new Intent();
                    intent.putExtra("type_id",type);
                    intent.setClass(activity, CompanyActivity.class);
                    activity.startActivityRightToLeft(intent);
                    return true;
                }
                if (url.contains("logout"))
                {
                    ServerApi.logout(SystemSet.getInstance().getToken(), new ServerCallBack() {
                        @Override
                        public void onError(Request request, Exception e) {
                            Log.e("error",e.getMessage());
                            Toast.makeText(getActivity(),"退出失败",Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(String response) throws JSONException {
                            Log.e("logout",response);
                            getActivity().recreate();
                            SystemSet.getInstance().clean(getActivity());
                            SystemSet.getInstance().removeAllCookie(webView);

                        }
                    });
                    return true;
                }
                else
                {
                    Intent intent = new Intent();

                    intent.putExtra("url",url);
                    intent.setClass(activity, MyWebActivity.class);
                    activity.startActivityRightToLeft(intent);
                    return true;
                }
            }
        });
    }

    @Override
    @JavascriptInterface
    public void requestObjectCFromHtml(String order)
    {
        Log.e("tag","order.....:"+order.toString());

        try
        {
            JSONObject orderObject = new JSONObject(order);
            WebViewJavascriptBridgeOrder webViewJavascriptBridgeOrder = WebViewJavascriptBridgeOrder.resolution(orderObject);
            checkOrder(webViewJavascriptBridgeOrder);
        }
        catch (Exception e)
        {
            Toast.makeText(getActivity(),getResources().getString(R.string.error_system),Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }


    private void checkOrder(WebViewJavascriptBridgeOrder webViewJavascriptBridgeOrder)
    {
        String action = webViewJavascriptBridgeOrder.action;

        if (action == null)
        {
            Toast.makeText(getActivity(),getResources().getString(R.string.error_system),Toast.LENGTH_LONG).show();
            return;
        }
        if (action.equals(WebViewJavascriptBridgeOrder.ACTION_LOGIN))
        {
            Intent intent = new Intent();
            intent.setClass(getActivity(), LoginActivity.class);
            ((Main2Activity) getActivity()).startActivityRightToLeft(intent);
            return;
        }
        if (action.equals(WebViewJavascriptBridgeOrder.ACTION_LOGOUT))
        {
            ServerApi.logout(SystemSet.getInstance().getToken(), new ServerCallBack() {
                @Override
                public void onError(Request request, Exception e) {
                    Log.e("error",e.getMessage());
                    Toast.makeText(getActivity(),"退出失败",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(String response) throws JSONException {
                    Log.e("logout",response);
                    getActivity().recreate();
                    SystemSet.getInstance().clean(getActivity().getApplication());
                    SystemSet.getInstance().removeAllCookie(webView);

                }
            });
            return;
        }

        if (action.equals(WebViewJavascriptBridgeOrder.ACTION_SHARE))
        {

                //({'action':'Share',data:{'title':'标题','images':'http://www.kldy8.com/images/logo.png','description':'描述'}});
                try
                {
                    WebViewJavascriptBridgeDataOrder data =  webViewJavascriptBridgeOrder.data;
                    if (data != null)
                    {
//                        String title = data.title;
//                        String images =  data.images;
//                        String description =  data.description;
////                     String url = dataJSONObject.optString("url");
//                        String url = nowUrl;
//                        showShare(title,images,description,url);
                    }
                    else
                    {
                        throw new Error();
                    }

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    Toast.makeText(this.getActivity(),getResources().getString(R.string.error_system),Toast.LENGTH_LONG).show();
                }
                return;


        }

        if (action.equals(WebViewJavascriptBridgeOrder.ACTION_SWITCHLOGIN))
        {
            Intent intent = new Intent();
            intent.setClass(getActivity(), LoginActivity.class);
            ((Main2Activity) getActivity()).startActivityRightToLeft(intent);
            return;
        }
    }




    private void showShare(String title, String images, String description, String url)
    {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，印象笔记、邮箱、信息、微信、人人网、QQ和QQ空间使用
        oks.setTitle(title);
        // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
        oks.setTitleUrl(url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(description);
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setImageUrl(images);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(url);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getResources().getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(url);

        // 启动分享GUI
        oks.show(getActivity());
    }
}
